<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>1.用键盘控制div</title>
  </head>
  <body>
    <pre>
        红色方块为键盘操作区域，您可以进行如下操作：
	
	上：↑ 下：↓ 左：← 右：→
	
	Ctrl + 1 : 背景变为绿色
	Ctrl + 2 : 背景变为黄色
	Ctrl + 3 : 背景变为蓝色
	Ctrl + ↑ : 放大
	Ctrl + ↓ : 缩小
    </pre>
    <div id="box"></div>
  </body>
  <style>
    body,
    div {
      margin: 0;
      padding: 0;
    }
    html,
    body {
      height: 100%;
    }
    #box {
      width: 50px;
      height: 50px;
      background: #0ff;
      position: absolute;
      left: 300px;
      top: 60px;
    }
  </style>
  <script>
    var oBox = document.getElementById("box");
    document.onkeydown = function (ev) {
      var oEvent = ev || window.event;
      var w = document.body.offsetWidth;
      var h = document.body.offsetHeight;
      var state = 0;
      switch (oEvent.keyCode) {
        case 37:
          oBox.offsetLeft == 0
            ? (oBox.style.left = 0)
            : (oBox.style.left = oBox.offsetLeft - 10 + "px");
          break;
        case 38:
          if (oEvent.ctrlKey == 1) {
            oBox.style.width = oBox.offsetWidth + 10 + "px";
            oBox.style.height = oBox.offsetHeight + 10 + "px";
          } else {
            oBox.offsetTop == 0
              ? (oBox.style.top = 0)
              : (oBox.style.top = oBox.offsetTop - 10 + "px");
          }
          break;
        case 39:
          console.log(w);
          console.log(oBox.offsetWidth);
          console.log(document.body.clientWidth);
          oBox.offsetLeft >= w - oBox.offsetWidth
            ? (oBox.style.left = w - oBox.offsetWidth)
            : (oBox.style.left = oBox.offsetLeft + 10 + "px");
          console.log(oBox.style.left);
          break;
        case 40:
          oEvent.ctrlKey == 1 &&
            ((oBox.style.width = oBox.offsetWidth - 10 + "px"),
            (oBox.style.height = oBox.offsetHeight - 10 + "px"));

          oBox.offsetTop >= h - oBox.offsetHeight
            ? (oBox.style.top = h - oBox.offsetHeight)
            : (oBox.style.top = oBox.offsetTop + 29 + "px");
          break;
        case 49:
          oEvent.ctrlKey == 1 && (oBox.style.background = "#0f0");
          return false;
          break;
        case 50:
          oEvent.ctrlKey == 1 && (oBox.style.background = "#ff0");
          return false;
          break;
        case 51:
          oEvent.ctrlKey == 1 && (oBox.style.background = "#00f");
          return false;
          break;
        default:
          break;
      }
      // function left() {
      // 	(oBox.offsetLeft == 0) ?
      // 	oBox.style.left = 0 :
      // 	oBox.style.left = (oBox.offsetLeft - 10) + "px";
      // }
    };
  </script>
</html>
